import VBAPI
from win32com import client
import traceback

CREO_APP = 'C:/Program Files/PTC/Creo 6.0.4.0/Parametric/bin/parametric.exe'
DIR = 'E:/python/test_data-3/'
cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)

#获取模型列表 递归
def get_modellist(Isession, filename,models):
    #检索模型
    ModelDescriptor = client.Dispatch(VBAPI.CCpfcModelDescriptor)
    mdlDescr = ModelDescriptor.CreateFromFileName(filename)
    RetriveModelOptions = client.Dispatch(VBAPI.CCpfcRetrieveModelOptions)
    options = RetriveModelOptions.Create()
    options.AskUserAboutReps = False
    model = Isession.RetrieveModelWithOpts(mdlDescr, options)
    #获取模型列表
    items = model.ListFeaturesByType(True, getattr(VBAPI.constants, 'EpfcFEATTYPE_COMPONENT'))
    for item in items:
        item_Descr = item.ModelDescr
        instancename = item_Descr.InstanceName
        extension = item_Descr.GetExtension()
        models.append({'filename': instancename, 'extension': extension})
        if extension == 'asm':
            get_modellist(Isession, item_Descr.GetFileName(), models)
    return models
AsyncConnection = cAC.Connect(None, None, None, None)
#AsyncConnection = cAC.Start(CREO_APP + ' -g:no_graphics -i:rpc_input', '')
ISession = AsyncConnection.Session
ISession.ChangeDirectory(DIR)
try:
    model = ISession.GetActiveModel()
    filename = model.FileName
    instancename = filename.split('.')[0]
    extension = filename.split('.')[1]
    items = get_modellist(ISession, filename, [{'filename': instancename, 'extension': extension}])
    for item in items:
        oldname = item['filename'] + '.' + item['extension']
        try:
            model = ISession.GetModelFromFileName(oldname)
            newname = 'test_' + item['filename']
            model.Rename(newname[:31] + '.' + item['extension'], True)
            model.Save()
        except Exception as e:
            pass

except Exception as e:
    print(traceback.print_exc())
finally:
    AsyncConnection.Disconnect(None)
